//
//  DayViewController.swift
//  YOKO
//
//  Created by Zoe_G on 16/5/4.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import UIKit
import RealmSwift

protocol DayViewControllerDelegate {
	func DayViewbackToMonthViewController()
	func switchToWeekViewController(date: NSDate)
}

class DayViewController: UIViewController, UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource, OneDayDetailDelegate {

	var date: NSDate? {
		didSet {
			self.initDateTitles()
			self.updateEvents()
		}
	}

	@IBOutlet weak var titleContentView: UIView!

	@IBOutlet weak var dayDetailView: UICollectionView!

	var weekViewButton: UIButton!
    
    var selectedDay: Int = 0

	var weekOverTitleView: WeekOverTitleView!

	var dayDateViews = [DateWithLunaView]()

	var delegate: DayViewControllerDelegate? = nil

	var eventList: [[EventInDayView]]! {
		didSet {
			self.dayDetailView.reloadData()
		}
	}

	var events: Results<Event>!

	var notificationToken: NotificationToken?

	deinit {
		if let notificationToken = notificationToken {
			notificationToken.stop()
		}
		NSNotificationCenter.defaultCenter().removeObserver(self)
	}

	override func viewDidLoad() {
		super.viewDidLoad()
		// 日期title下面阴影
		titleContentView.layer.shadowOffset = CGSizeMake(0, 2)
		titleContentView.layer.shadowColor = UIColor.lightGrayColor().CGColor
		titleContentView.layer.shadowRadius = 3
		titleContentView.layer.shadowOpacity = 0.4

		initsubView()

		let realm = try! Realm()
		notificationToken = realm.addNotificationBlock { notification, realm in
			self.updateEvents()
			self.dayDetailView.reloadData()
		}

		NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DayViewController.changeCalendar(_:)), name: YOKONotification.CHANGE_CURRENT_CALENDAR, object: nil)
	}
    
    override func viewDidLayoutSubviews() {
        // 根据所选天，滚到相应位置
        dayDetailView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: selectedDay-1, inSection: 0), atScrollPosition: .Left, animated: false)
    }

	func changeCalendar(notification: NSNotification) {
		self.updateEvents()
		self.dayDetailView.reloadData()
	}

	override func viewWillAppear(animated: Bool) {
		super.viewWillAppear(animated)

	}

	func updateEvents() {

		var currentHour = 0

		// components.day = j + 7 * i - firstWeekday + 1
		// components.minute = 0
		// components.second = 0
		// components.hour = 0
		// let dayBegin = calendar.dateFromComponents(components)
		// components.hour = 24
		// let dayEnd = calendar.dateFromComponents(components)
		// dayEvent = uiRealm.filter("timeBegin < %@ AND timeEnd > %@", dayEnd!, dayBegin!)

		eventList = [[EventInDayView]]()

		let weekBegin = NSDate.beginOfDay(NSDate.firstDayOfWeek(self.date!))
		let weekEnd = NSDate.endOfDay(NSDate.lastDayOfWeek(self.date!))
		let totalEvents = uiRealm.objects(Event).filter("timeBegin < %@ AND timeEnd > %@ AND calendarId = %@", weekEnd, weekBegin, NSUserDefaults.getCurrentCalendarId())

		for i in 0 ... 6 {
			currentHour = 0
			var singleDayEventList = [EventInDayView]()

			let day = NSDate.theNextDays(weekBegin, day: i)
			let dayBegin = NSDate.beginOfDay(day)
			let dayEnd = NSDate.endOfDay(day)
			events = totalEvents.filter("timeBegin < %@ AND timeEnd > %@ ", dayEnd, dayBegin).sorted("timeBegin")

			let formatter = NSDateFormatter()
			formatter.dateFormat = "HH:mm"

			// 插入全天事件
			for i in events {
				if (i.getEventType() <= 1) {
					let event = EventInDayView()
					event.isEmpty = false
					event.colorType = i.type
					event.eventDescription = i.descriptions
					event.eventLocation = i.location
					event.eventType = i.getCircleIconType(dayBegin, dateEnd: dayEnd)
					event.eventTitleText = i.summary
                    event.eventLocalId = i.localId
                    event.event = i
                    if (i.wholeDayEvent) {
                        if (!i.timeBegin.isInSameDayAsDate(i.timeEnd)) {
                            event.eventBeginTime = "跨天"
                        } else {
                            event.eventBeginTime = "全天"
                        }
                    } else if (!i.timeBegin.isInSameDayAsDate(i.timeEnd)) {
                        if (i.timeBegin.isInSameDayAsDate(dayBegin)) {
                            event.eventBeginTime = formatter.stringFromDate(i.timeBegin)
                            event.eventEndTime = "跨天"
                        } else if (i.timeEnd.isInSameDayAsDate(dayBegin)) {
                            event.eventBeginTime = "跨天"
                            event.eventEndTime = formatter.stringFromDate(i.timeEnd)
                        } else {
                            event.eventBeginTime = "跨天"
                        }
					}
					singleDayEventList.append(event)
				}
			}

			// 插入非全天事件
			for i in events {
				if (i.getEventType() > 1) {
					if (i.timeBegin.hour > currentHour) {
                        if (i.timeBegin.minute == 0) {
                            for i in currentHour ..< i.timeBegin.hour {
                                let event = EventInDayView()
                                event.emptyTime = i
                                singleDayEventList.append(event)
                            }
                        } else {
                            for i in currentHour ... i.timeBegin.hour {
                                let event = EventInDayView()
                                event.emptyTime = i
                                singleDayEventList.append(event)
                            }
                        }
					}
					let event = EventInDayView()
					event.isEmpty = false
					event.colorType = i.type
					event.eventDescription = i.descriptions
					event.eventLocation = i.location
					event.eventType = i.getCircleIconType(dayBegin, dateEnd: dayEnd)
					event.eventTitleText = i.summary
                    event.eventBeginTime = formatter.stringFromDate(i.timeBegin)
                    event.eventLocalId = i.localId
                    event.event = i
					if (i.getEventType() != 2) {
						event.eventEndTime = formatter.stringFromDate(i.timeEnd)
					}
					singleDayEventList.append(event)
					if (i.timeEnd.hour >= currentHour) {
//						if (i.timeEnd.minute != 0) {
//							currentHour = i.timeEnd.hour + 1
//						} else {
//							currentHour = i.timeEnd.hour
//						}
                        currentHour = i.timeEnd.hour + 1
					}
				}
			}

			// 插入剩余的时间段
			if (currentHour < 23) {
				for i in currentHour ... 23 {
					let event = EventInDayView()
					event.emptyTime = i
					singleDayEventList.append(event)
				}
			}

//            NSLog("singleDayEventList.count == %i", singleDayEventList.count)

			eventList.append(singleDayEventList)
		}
	}

	func initDateTitles() {
		// 计算时间是周几，设置选中view
		selectedDay = NSDate.weekDay(self.date!)

		// 计算当前时间所在周的第一天
		let firstDay = NSDate.firstDayOfWeek(self.date!)
		let components = NSDateComponents()

		for view in dayDateViews {
			view.removeFromSuperview()
		}

		dayDateViews.removeAll()

		for i in 0 ... 6 {
			let dateView = NSBundle.mainBundle().loadNibNamed("DateWithLunaView", owner: self, options: nil).last as? DateWithLunaView
			components.day = i
			let date = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: firstDay, options: .MatchStrictly)

			dateView?.date = date
			if i + 1 == selectedDay {
				dateView!.isSelected = true
			}
			dateView?.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(self.backToMonthView)))

			dateView?.frame = CGRectMake((screenWidth / 7) * CGFloat(i), 24, screenWidth / 7, 30)
			self.view.addSubview(dateView!)
			dayDateViews.append(dateView!)
		}

	}

	func initsubView() {

		weekOverTitleView = NSBundle.mainBundle().loadNibNamed("WeekOverTitleView", owner: self, options: nil).last as? WeekOverTitleView

		weekOverTitleView!.frame = CGRectMake(0, 0, screenWidth, 24)
		self.view.addSubview(weekOverTitleView!)

		let layout = UICollectionViewFlowLayout()

		layout.itemSize = CGSizeMake(screenWidth, screenHeight - 54 - 64 - 8 - 49)
//        layout.itemSize = CGSizeMake(screenWidth, self.dayDetailView.bounds.height)
		layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
		layout.minimumLineSpacing = 1.0
		layout.minimumInteritemSpacing = 1.0
		layout.scrollDirection = UICollectionViewScrollDirection.Horizontal

		dayDetailView.setCollectionViewLayout(layout, animated: true)
		dayDetailView.registerNib(UINib(nibName: "OneDayDetailTableView", bundle: nil), forCellWithReuseIdentifier: "OneDayDetailTableView")
		dayDetailView.dataSource = self
		dayDetailView.delegate = self
		self.dayDetailView.backgroundColor = UIColor.clearColor()
		dayDetailView.bounces = false

	}

	// MARK: - collectionViewDataSource
	func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

		return 7

	}

	func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
		return 1
	}

	// MARK: - collectionViewDelegate
	func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
		let cell = collectionView.dequeueReusableCellWithReuseIdentifier("OneDayDetailTableView", forIndexPath: indexPath) as! OneDayDetailTableView

		cell.eventList = self.eventList[indexPath.row]
        //计算每个cell对应的时间
        let firstDay = NSDate.firstDayOfWeek(self.date!)
        let components = NSDateComponents()
        components.day = indexPath.row
        let date = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: firstDay, options: .MatchStrictly)
        cell.date = date
        cell.oneDaydelegate = self

		return cell
	}

	func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {

		let offsetX = scrollView.contentOffset.x
		let width = scrollView.bounds.size.width

		let offset = offsetX / width

		let currentrow = lrintf(Float(offset))
        selectedDay = currentrow+1
		self.dayDetailView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: currentrow, inSection: 0), atScrollPosition: .Left, animated: true)

		if decelerate {

			scrollView.decelerationRate = 0.5
		}

		for i in 0 ... dayDateViews.count - 1 {
			if i == currentrow {
				dayDateViews[i].isSelected = true
			} else {
				dayDateViews[i].isSelected = false
			}
		}
	}

	func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

		let offsetX = scrollView.contentOffset.x
		let width = scrollView.bounds.size.width

		let offset = offsetX / width

		let currentrow = lrintf(Float(offset))
        selectedDay = currentrow+1
		self.dayDetailView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: currentrow, inSection: 0), atScrollPosition: .Left, animated: true)

		for i in 0 ... dayDateViews.count - 1 {
			if i == currentrow {
				dayDateViews[i].isSelected = true
			} else {
				dayDateViews[i].isSelected = false
			}
		}

	}

	@IBAction func switchToWeekView() {
		self.delegate?.switchToWeekViewController(self.date!)
	}

	@IBAction func backToMonthView() {
		self.delegate?.DayViewbackToMonthViewController()
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
	}
    
    //MARK:- OneDayDetailDelegate
    func showInstantAddView(withDate: NSDate, isWholeDayEvent: Bool) {
        let instantView = NSBundle.mainBundle().loadNibNamed("InstantAddDetailView", owner: self, options: nil).last as! InstantAddDetailView
        instantView.frame = CGRectMake(0, 56, screenWidth, screenHeight )
        
        instantView.isWholeDay = isWholeDayEvent
        if isWholeDayEvent {
            let com = NSDateComponents()
            com.second = 1
            instantView.date = withDate.add(com)
            instantView.timeLabel.text = "全天"
        } else {
            instantView.date = withDate
            let formatter = NSDateFormatter()
            formatter.dateFormat = "HH:mm"
            instantView.timeLabel.text = formatter.stringFromDate(withDate)
        }
        self.view.addSubview(instantView)
    }
}
